package com.lagou.controller;

import com.lagou.entity.Order;
import com.lagou.entity.OrderDetail;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/placeOrder")
    public String placeOrder(Model model)
            throws ExecutionException, InterruptedException {

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setItemId(UUID.randomUUID().toString());
        orderDetail.setItemName("荣耀");
        orderDetail.setItemPrice(2000);
        orderDetail.setNum(1);
        List<OrderDetail> details = new ArrayList<>(1);
        details.add(orderDetail);

        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString());
        order.setUserId(UUID.randomUUID().toString());
        order.setStatus("0");
        order.setDetails(details);

        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("ex.order", "k.order", order, correlationData);

        CorrelationData.Confirm confirm = correlationData.getFuture().get();

        boolean isAcked = confirm.isAck();

        if(!isAcked) {
            return "failure";
        }

        rabbitTemplate.convertAndSend("ex.order.ttl", "k.order.ttl", order.getOrderId());

        model.addAttribute("orderId", order.getOrderId());

        return "waitingForPay";
    }

    @GetMapping("/failureOrder/{orderId}")
    public String failureOrder(@PathVariable String orderId, Model model) {
        model.addAttribute("orderId", orderId);
        return "failure";
    }
}
